<template>
  <div :class="['signature_flex', signClass]">
    <div
      :class="['signature_box', disabled ? 'signature_box_disabled' : '']"
      :style="{
        width: canvasConfig.width ? canvasConfig.width + 'px' : '660px',
        height: canvasConfig.height ? canvasConfig.height + 'px' : '240px',
      }"
    >
      <img v-if="disabled" :src="signatureUrl" style="width: 100%; height: auto" />
      <div v-else class="tipBox">
        <sign-canvas
          ref="signRef"
          :canvasConfig="{ width: 660, height: 240, ...canvasConfig }"
        ></sign-canvas>
      </div>
      <img
        v-if="!disabled"
        class="delete_signature"
        src="@/assets/image/icon_Delete.png"
        @click.stop="deleteSignature"
      />
    </div>
    <div
      :class="['signature_mobile', 'signature_mobile_' + disabled]"
      :style="{
        width: canvasConfig.height ? canvasConfig.height + 'px' : '240px',
        height: canvasConfig.height ? canvasConfig.height + 'px' : '240px',
      }"
    >
      <img src="@/assets/image/qrCode.png" />
      <span>
        <u @click="getQrCode">Draw from your mobile device</u>
      </span>
    </div>
  </div>
  <sign-color
    v-if="showColor"
    ref="signColorRef"
    v-bind="signColorConfig"
    @changeColor="changeColor"
  />
  <qr-code-dialog
    ref="QrCodeDialogRef"
    :qrCodeConfig="qrCodeConfig"
    @handleRefresh="handleRefresh"
    @getQRInfo="getQRInfo"
  />
</template>
<script setup>
import _ from 'lodash';
import { ElMessage } from 'element-plus';

import QrCodeDialog from './QrCodeDialog.vue';
import SignColor from './SignColor.vue';
import SignCanvas from './SignCanvas.vue';
import { apiMethods } from '@/utils/http.js';

const attrs = useAttrs();

const props = defineProps({
  showColor: {
    // 是否展示颜色
    type: Boolean,
    default: true,
  },
  signClass: {
    type: String,
    default: '',
  },

  signConfig: {
    // 签名配置
    type: Object,
    default: () => ({}),
  },
  qrCodeConfig: {
    // 二维码配置
    type: Object,
    default: () => ({}),
  },
  canvasConfig: {
    // 画布配置
    type: Object,
    default: () => ({
      width: 660,
      height: 240,
    }),
  },
  signColorConfig: {
    // 签名颜色配置
    type: Object,
    default: () => ({}),
  },
});

const signatureUrl = ref('');

const QrCodeDialogRef = ref();
const signRef = ref();
const timer = ref();
const timeTotal = ref(0);
const qrInfo = ref({});
const formData = ref({});

const disabled = computed(() => {
  const { disabled, disabledFn } = attrs;
  if (disabled) return disabled;
  if (disabledFn && _.isFunction(attrs.disabledFn)) {
    return disabledFn(formData.value);
  }
});

function init(sign, row) {
  signRef.value.initCanvas(sign);
  formData.value = row;
}

// 组件销毁，清除定时器
onUnmounted(() => {
  if (timer.value) clearInterval(timer.value);
});

// 删除签名
function deleteSignature() {
  signRef.value.clearDraw();
}

// 打开二维码
function getQrCode() {
  if (disabled.value) return;
  QrCodeDialogRef.value.init();
  getPoll();
}

// 打开二维码进行轮询
function getPoll() {
  timeTotal.value = 0;
  if (timer.value) clearInterval(timer.value);
  timer.value = setInterval(() => {
    timeTotal.value += 5;
    if (timeTotal.value >= 300) {
      clearInterval(timer.value);
      return;
    }
    getMobileSign();
  }, 5000);
}

// 获取移动端签名
function getMobileSign() {
  const { axiosMethod = 'post', params, requestUrl } = props.signConfig;
  if (!requestUrl) {
    if (timer.value) clearInterval(timer.value);
    return;
  }
  apiMethods[axiosMethod](requestUrl, params)
    .then(res => {
      let data = res.data.data;
      if (
        data &&
        data.signatureCode === qrInfo.value.signatureCode &&
        (data.signatureUrl || data.signature)
      ) {
        signatureUrl.value =
          apiMethods.filter_url('/attachmentsFiles/downloadFileReadOnly?url=') +
          (data.signatureUrl || data.signature);
        signRef.value?.initCanvas && signRef.value.initCanvas(signatureUrl.value);
        clearInterval(timer.value);
        QrCodeDialogRef.value.buttonClick('close');
      }
    })
    .catch(res => {
      if (timer.value) clearInterval(timer.value);
    });
}

// 获取二维码信息
function getQRInfo(row) {
  qrInfo.value = row;
}

// 刷新二维码，重新轮询
function handleRefresh() {
  getPoll();
}

// 初始化画布
function initCanvas(val) {
  if (disabled.value) {
    signatureUrl.value = val;
  } else {
    signRef.value.initCanvas(val);
  }
  // signRef()
}

// 获取画布信息
function getCanvasInfo(cb) {
  signRef.value.canvasHandler(res => {
    if (res) {
      cb && cb(res);
    } else {
      ElMessage.warning('Please Signature');
      return;
    }
  });
}

// 修改画布颜色
function changeColor(val) {
  signRef.value.setStrokeStyle(val);
}

defineExpose({
  init,
  getCanvasInfo,
  initCanvas,
});
</script>
<style lang="scss" scoped>
.signature_flex {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;
}

.signature_box {
  border-radius: 4px;
  margin-right: 10px;
  border: 1px dashed var(--el-color-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  .hoverTips {
    opacity: 0;
  }
  .tipBox {
    position: absolute;
    font-size: 12px;
    color: var(--el-color-primary);
    img {
      margin-right: 8px;
      position: relative;
      top: 2px;
    }
  }
  &:hover {
    // background-color: rgba($color: #000000, $alpha: 0.2);
    .hoverTips {
      opacity: 1;
    }
  }
  .delete_signature {
    position: absolute;
    transform: scale(1.2);
    cursor: pointer;
    top: 10px;
    right: 10px;
  }
}

.signature_box_disabled {
  background: #f5f7fa;
  cursor: not-allowed;
}

.signature_mobile {
  border: 1px solid #ccc;
  border-radius: 4px;
  position: relative;
  img {
    position: absolute;
    width: calc(100% - 20px);
    height: calc(100% - 20px);
    top: 10px;
    left: 10px;
  }
  span {
    width: calc(100% - 2px);
    height: calc(100% - 2px);
    background: rgba(255, 255, 255, 0.9);
    position: absolute;
    z-index: 10;
    top: 1px;
    left: 1px;
    padding: 0 20px;
    box-sizing: border-box;
    text-align: center;
    line-height: 22px;
    display: flex;
    align-items: center;
    justify-content: center;
    u {
      color: var(--el-color-primary);
      cursor: pointer;
    }
  }
}
.signature_mobile_true {
  u {
    cursor: not-allowed !important;
  }
}

.signature_rfi_rfa_dialog {
  margin-bottom: 20px;
  .signature_box {
    width: 660px;
    height: 240px;
  }
  .tipBox {
    height: 240px;
  }
  .signature_mobile {
    width: 240px;
    height: 240px;
    img {
      width: 200px;
      height: 200px;
      top: 20px;
      left: 20px;
    }
    span {
      width: 238px;
      height: 238px;
    }
  }
}
</style>
